from http.server import HTTPServer, BaseHTTPRequestHandler,SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn
import os
import json
#pip3 install requests -i https://pypi.doubanio.com/simple
from urllib.parse import urlparse,urlencode,quote

data = {'result': 'this is a test'}
host = ('0.0.0.0', 8888)

current_directory = os.getcwd()

#是否忽略文件,True 不忽略
def no_ignore_file(tmp):
    for a in ['mp4','rmvb','avi','rm','wmv','3gp','mkv','mov','flv','mpeg','webm','m3u8'
    ,'jpg','png','bmp','jpeg','gif']:
        if tmp.endswith('.'+a):
            return True
    return False
    

class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

 
def print_files_in_folder(folder_path,file_list,url_path):
    for item in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item)
        url_path_tmp=url_path+'/'+item
        if os.path.isdir(item_path):
            file_tmp=[]
            print_files_in_folder(item_path,file_tmp,url_path_tmp)  # 递归调用
            file_list.append({
                'url': quote(url_path_tmp),
                'type': 0,'name':item,
                'childs':file_tmp
            })
        else:
            if no_ignore_file(item):
                file_list.append({
                'url': quote(url_path_tmp),
                'type': 1,'name':item
                })
            #print(item_path)  # 执行操作，例如打印文件路径
            #print(item)  # 执行操作，例如打印文件路径
 

class MyHttpHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        parsed_path = urlparse(self.path)
        print("URL path= %s" % parsed_path.path)
        if parsed_path.path == '/api/json':
            print("get /api/json start!!" )
        # 获取当前工作目录
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            #self.wfile.write(json.dumps(data).encode())
            self.wfile.write(json.dumps(file_list_data).encode())
            print("get /api/json end!!" )
        else:
            super().do_GET()
'''
    super(self)
'''
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    pass
if __name__ == '__main__':
    file_list_data = []
    print_files_in_folder(current_directory,file_list_data,'')
    print("Starting server, listen at: %s:%s" % host)

    #多线程
    httpd = ThreadedHTTPServer(host, MyHttpHandler)
    httpd.serve_forever()
    '''
    server = HTTPServer(host, MyHttpHandler)
   
    #print(file_list_data)
    print("dir files load end!!" )
    server.serve_forever()
    '''
    #最原始的方式
    '''
    server = HTTPServer(host,SimpleHTTPRequestHandler)
    server.serve_forever()
     '''